using Glpt.Data;
using System;
using System.Collections.Generic;
using System.Data;

namespace Glpt.Common
{
    /// <summary>
    /// 交易日信息类
    /// </summary>
    public class TradeDays
    {
        /// <summary>
        /// 交易日
        /// </summary>
        private static Dictionary<double, string> Dict = new Dictionary<double, string>();
        /// <summary>
        /// 缓存日
        /// </summary>
        private static string CacheDay = "";
        /// <summary>
        /// 获取交易日
        /// </summary>
        /// <param name="val">相差天数</param>
        /// <param name="stdtime">基准时间</param>
        /// <returns>交易日</returns>
        public static string GetTradeDate(double val, DateTime stdtime)
        {
            string busi_date = stdtime.ToString("yyyyMMdd");
            string cur_date = ServerTime.ServerDateTime.ToString("yyyyMMdd");
            if (!cur_date.Equals(busi_date))
            {
                return GetNTradedate(val, busi_date);
            }
            lock (CacheDay)
            {
                if (!CacheDay.Equals(cur_date))
                {
                    CacheDay = cur_date;
                    BaseInterFace bif = new BaseInterFace();
                    DataTable dt = bif.GetTradeDays();
                    Dict.Clear();
                    foreach (DataRow dr in dt.Rows)
                    {
                        Dict.Add(double.Parse(dr["TRADE_DAYS"].ToString()), dr["TRADEDATE"].ToString());
                    }
                }
            }
            if (Dict.ContainsKey(val))
                return Dict[val];
            else
                return GetNTradedate(val, busi_date);
        }

        private static string GetNTradedate(double val, string busi_date)
        {
            BaseInterFace bif = new BaseInterFace();
            DataTable dt = bif.ExecSelect("SELECT " + bif.FunctionChar + "GET_N_TRADEDATE(" + busi_date + "," + val.ToString() + ") FROM DUAL");
            return dt.Rows[0][0].ToString();
        }
    }
}
